package com.netty.netty.high.demo1;

import com.netty.util.ByteBufferUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyServer {

    private static final Logger log= LoggerFactory.getLogger(NettyServer.class);

  public static void main(String[] args) {

      NioEventLoopGroup boss = new NioEventLoopGroup(1);
      NioEventLoopGroup worker = new NioEventLoopGroup(6);

    new ServerBootstrap()
        .group(boss, worker)
        .channel(NioServerSocketChannel.class)
        // 半包问题：例如，发送方发送100字节数据，而接收方最多只能接收30字节数据，这就是半包问题
            //option(ChannelOption.SO_RCVBUF,10),调整接收缓冲区大小（滑动窗口）
        .option(ChannelOption.SO_RCVBUF,10)
        .childHandler(
            new ChannelInitializer<NioSocketChannel>() {
              @Override
              protected void initChannel(NioSocketChannel ch) throws Exception {

                // 不进行加解密不然展示不出粘包效果
                //                      ch.pipeline().addLast(new StringDecoder());

                ch.pipeline().addLast(new LoggingHandler());

                ch.pipeline()
                    .addLast(
                        new ChannelInboundHandlerAdapter() {

                          @Override
                          public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            log.info("客户端已成功连接服务器");
                            super.channelActive(ctx);
                          }

                          @Override
                          public void channelRead(ChannelHandlerContext ctx, Object msg)
                              throws Exception {

                            log.info("msg={}", msg);
                            super.channelRead(ctx, msg);
                          }
                        });
              }
            })
        .bind(8080);
  }

}
